package wxshop.web.user.tool;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;
import wxshop.api.user.model.User;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * Created by yvdedu.com on 2018/1/10.
 */
@Component
public class JwtTool {
	
	private static final String KEY = "as,d.r/s+=*.,f/.,f5";
	
	@Resource
	private ObjectMapper objectMapper;
	
	//把token解出来
	public User toUser(String token ) throws IOException {
		return objectMapper.readValue(Jwts.parser().setSigningKey(KEY).parseClaimsJws(token).getBody().getSubject(),User.class);
	}
	
	
	//把token写出去
	public String toJwt( User user ) throws JsonProcessingException {
		return Jwts.builder()
				.setSubject(objectMapper.writeValueAsString(user))
//				.setExpiration(new Date(SysManageService.currentTimeMillis()+1000*60*60*24))//设置token过期时间为1天 绑定在token上
				.signWith(SignatureAlgorithm.HS512, KEY)
				.compact();
	}
	
}
